// Created by lifei on 2020/7/20--11:17.
import pager from "@/assets/js/page-mixin";
import {
    searchUseCardList,
    deleteRowById,
    exportUseCardList,
    doRecoveryUseCard,
    doPrintingList
} from "@/views/authorization-management/use-card/api/use-card.js";
import { console } from "vuedraggable/src/util/helper";
import { getDict } from "~/utils";
import propertyView from "~/views/authorization-management/use-card/propertyView/propertyView.vue";
import { mapGetters } from "vuex";
import printJS from 'print-js'

export default {
    name: "resource-manage",
    mixins: [pager],
    components: {
        propertyView
    },
    computed: {
        ...mapGetters(["permissions"])
    },
    provide () {
        return {
            initList: this.query,
        };
    },
    beforeMount () {
        this.query();
    },
    data () {
        return {
            sumArea: '',
            unitName: '',
            authorizationNumber: '',
            useCardPropertyList: [],
            dialogVisible: false,
            loading: true,
            //按钮权限
            addUseCardBut: false,
            deleteUseCardBut: false,
            updateUseCardBut: false,
            //表单数据
            tableData: [],
            //分页数据
            // 请求参数
            params: {
                current: 1,
                size: 10,
                keyword: ''
            },
            // 选中的数据
            selectDataArr: [],
            // 分页
            pager: {
                total: 0, // 总页数
                current: 1, // 当前页数
                size: 20 // 每页显示多少条
            },

            multipleSelection: [],
            // 传入过滤条件里面的内容
            filterList: [
                {
                    label: "授权号",
                    name: "authorizationNumber",
                    type: "input",
                },
                {
                    label: "授权日期",
                    name: ["authorizationTimeStart", "authorizationTimeEnd"],
                    inputType: "daterange",
                    // model: "authorizationDate"
                },
                {
                    label: "授权状态",
                    name: 'authorizationStatus',
                    inputType: 'select',
                    children: [
                        {
                            value: "已发放",
                            label: "已发放"
                        },
                        {
                            value: "未发放",
                            label: "未发放"
                        }
                    ]
                },
                {
                    label: "收回状态",
                    name: "recoveryStatus",
                    inputType: 'select',
                    children: [
                        {
                            value: '0',
                            label: "正常"
                        },
                        {
                            value: '1',
                            label: "已回收"
                        }
                    ]
                }
            ],
        };
    },
    //载入事件
    mounted: function () {
        //按钮权限
        this.addUseCardBut = this.permissions["addUseCardBut"];
        this.deleteUseCardBut = this.permissions["deleteUseCardBut"];
        this.updateUseCardBut = this.permissions["updateUseCardBut"];
        //查询
        this.query();
    },
    methods: {

        // 菜单点击监听
        handleMenuClick (type) {
            switch (type) {
                case 'add':
                    this.$router.push("/permission-manage/use-card-add");
                    break;
                case 'test':
                    this.doPrinting()
                    break;
                case 'export':
                    this.exportUseCard()
                    break;
            }
        },

        beforeClose (done) {
            this.dialogVisible = false;
        },
        getListData () {
            console.log(this.pageParams);
        },
        /**
 * 获取打印信息(按钮打印)
 */
        doPrinting () {
            if (this.multipleSelection.length == 0) {
                this.$alert("请选择一个需要打印的使用证", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            if (this.multipleSelection.length > 1) {
                this.$alert("请勿选择多个使用证", "提示", {
                    confirmButtonText: "确定"
                });
                return;
            }
            doPrintingList(this.multipleSelection[0].useCardId)
                .then(resp => {
                    this.dialogVisible = true
                    this.authorizationNumber = resp.data.data.useCard.authorizationNumber
                    this.unitName = resp.data.data.useCard.unitName
                    this.sumArea = resp.data.data.sumArea
                    this.useCardPropertyList = resp.data.data.useCardPropertyList
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "操作失败"
                    });
                })
                .finally(() => (this.loading = false));

        },
        /**
         * 获取打印信息（列表操作字段的打印）
         */
        doPrintingOne (scope) {
            doPrintingList(scope.row.useCardId)
                .then(resp => {
                    this.dialogVisible = true
                    this.authorizationNumber = resp.data.data.useCard.authorizationNumber
                    this.unitName = resp.data.data.useCard.unitName
                    this.sumArea = resp.data.data.sumArea
                    this.useCardPropertyList = resp.data.data.useCardPropertyList
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: "操作失败"
                    });
                })
                .finally(() => (this.loading = false));
        },
        submit () {
            printJS({
                printable: 'printTemplate',
                type: 'html',
                frameId: 'printFrame',
                style: this.getPrintStyle(),
                scanStyles: false,  //扫描页面样式
                targetStyles: ['*'],
            })
        },

        getPrintStyle () {
            return `
         .template-head{
            align-content: center;
            width: 100%;
            margin-top: 10px;
            margin-left: 2%;
          }
          
          .approve-form-table{
            align-content: center;
            vertical-align: center;
            text-align: center;
          }
          
          table{
              font-size:12px;
            border: solid #bfbfbf 1px;
            border-collapse: collapse;
            padding: 10px 20px;
            max-width: 100%;
          }
          tr{
            height: 50px;
          }
          td{
            border: solid #bfbfbf 1px;
            padding: 10px 20px;
          }
          th{
            border: solid #bfbfbf 1px;
            padding: 10px 20px;
          }
          
          .table-input{
            width: 90%;
            float: left;
          }
          
          .table-div{
            width: 96%;
            align-content: center;
            margin: 30px auto;
          }
          
          .template-head-font{
            font-size: 14px;
            width: 88%;
          }
          
          .head-time{
            font-size: 14px;
            float: right;
            margin-right: 4%;
          }
          .propertyName{
              width:50px;
          }
          .authorizationUse{
              width:50px;
          }
            `

        },
        handleClick (item) { },
        /**
         * 跳转到新增页面
         */
        /*  toAdd: function() {
              this.$router.push("/permission-manage/use-card-add");
          },*/

        /**
         * 跳转到编辑页面
         * @param scope
         */
        toEditData: function (scope) {
            this.$router.push({
                path: "/permission-manage/use-card-edit",
                query: { useCardId: scope.row.useCardId }
            });
        },

        /**
         * 跳转到变更页面
         * @param scope
         */
        toChange: function (scope) {
            this.$router.push({
                path: '/permission-manage/use-card-change',
                query: { useCardId: scope.row.useCardId }

            });
        },

        /**
         * 跳转到查看页面
         * @param scope
         */
        toDetail (scope) {
            this.$router.push({
                path: '/permission-manage/use-card-detail',
                query: { useCardId: scope.row.useCardId }

            });
        },
        toWindowApplyList (scope) {
            this.$refs.propertyView.show(scope.row);
        },
        /**
         * 查询方法
         * @param param
         */
        query (params = {}) {
            this.loading = true;
            let req = { ...this.params, ...params }
            !req.authorizationStatus && delete req.authorizationStatus;
            !req.recoveryStatus && delete req.recoveryStatus;
            !req.autthorizationDateEnd && delete req.autthorizationDateEnd;
            !req.authorizationDateStart && delete req.authorizationDateStart;
            !req.authorizationNumber && delete req.authorizationNumber;
            searchUseCardList(req).then((res) => {
                const { current, size, total, records } = res.data.data
                this.tableData = records
                this.params = req
                this.pager = { total, current, size }
            }).catch(error => {
                this.$message({
                    type: "error",
                    message: "查询失败"
                });
            })
                .finally(() => (this.loading = false));
        },
        /**
         * 列表导出
         */
        exportUseCard () {
            exportUseCardList(this.searchKeyword, 1, 10000).then(res => {
                // 关闭loading
                this.loading = false;
                // 此处有个坑。这里用content保存文件流，最初是content=res，但下载的test.xls里的内容如下图1，
                // 检查了下才发现，后端对文件流做了一层封装，所以将content指向res.data即可
                // 另外，流的转储属于浅拷贝，所以此处的content转储仅仅是便于理解，并没有实际作用=_=
                const content = res.data;
                const blob = new Blob([content]); // 构造一个blob对象来处理数据
                const fileName = "使用证列表.xls"; // 导出文件名
                // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                // IE10以上支持blob但是依然不支持download
                if ("download" in document.createElement("a")) {
                    // 支持a标签download的浏览器
                    const link = document.createElement("a"); // 创建a标签
                    link.download = fileName; // a标签添加属性
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click(); // 执行下载
                    URL.revokeObjectURL(link.href); // 释放url
                    document.body.removeChild(link); // 释放标签
                } else {
                    // 其他浏览器
                    navigator.msSaveBlob(blob, fileName);
                }
                this.btnSendTem = false;
            });
        },


        /**
         * 删除
         * @param scope
         */
        deleteRow (scope) {
            this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    console.log(scope.row);

                    deleteRowById(scope.row.useCardId)
                        .then(resp => {
                            this.query();
                        })
                        .catch(error => {
                            this.$message({
                                type: "error",
                                message: "操作失败"
                            });
                        })
                        .finally(() => (this.loading = false));

                    this.$message({
                        type: "success",
                        message: "删除成功!"
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        },

        /**
         * 回收
         * @param scope
         */
        doRecovery (scope) {
            this.$confirm("此操作将回收该记录, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    console.log(scope.row);

                    doRecoveryUseCard(scope.row.useCardId)
                        .then(resp => {
                            this.query();
                        })
                        .catch(error => {
                            this.$message({
                                type: "error",
                                message: "操作失败"
                            });
                        })
                        .finally(() => (this.loading = false));

                    this.$message({
                        type: "success",
                        message: "回收成功!"
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消回收"
                    });
                });
        },
    }
};
